package cn.flyboy.controller;

import java.io.*;
import java.util.*;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import cn.flyboy.entity.*;
import cn.flyboy.service.ExamService;
import cn.flyboy.service.InfoService;
import cn.flyboy.service.StudentService;
import cn.flyboy.service.TeacherService;
import cn.flyboy.utils.ConfigUtils;
import cn.flyboy.utils.FileHelper;
import cn.flyboy.utils.PagingSize;
import cn.flyboy.utils.ZipUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class TeacherController {
    @Resource
    private TeacherService teacherServiceImpl;
    @Resource
    private ExamService examServiceImpl;
    @Resource
    private InfoService infoServiceImpl;
    @Resource
    private StudentService studentServiceImpl;


    @RequestMapping("goStudentInfo")
    public String goStudentInfo(int id, HttpSession session) {
        Object obj = session.getAttribute("examStartName");
        String exam = null;
        if (obj == null) {
            List<Exam> exams = examServiceImpl.selStartExam();
            if (exams.size() > 1) {
                session.setAttribute("info", "<script>alert('当前存在多场考试，请联系管理员');</script>");
                System.out.println("当前存在多场考试，请联系管理员");
                return "redirect:/teacher/teacher_exam_before.jsp";
            } else if (exams.size() < 1) {
                session.setAttribute("info", "<script>alert('当前不存在考试');</script>");
                System.out.println("当前不存在考试");
                return "redirect:/teacher/teacher_exam_before.jsp";
            } else {
                exam = exams.get(0).getE_name();
                session.setAttribute("examStartName", exam);
            }
        } else {
            exam = (String) obj;
            session.setAttribute("examStartName", exam);
        }
        if (id == 1) {
            session.setAttribute("teacher", session.getAttribute("teacher"));
            return "redirect:/teacher/teacher_exam_condition.jsp";
        } else if (id == 2) {
            session.setAttribute("teacher", session.getAttribute("teacher"));
            return "redirect:/teacher/teacher_studentInfo.jsp";
        } else if (id == 3) {
            session.setAttribute("teacher", session.getAttribute("teacher"));
            return "redirect:/teacher/teacher_unlocked.jsp";
        } else if (id == 4) {
            session.setAttribute("teacher", session.getAttribute("teacher"));
            return "redirect:/teacher/teacher_notify.jsp";
        }
        session.setAttribute("teacher", session.getAttribute("teacher"));
        return "redirect:/teacher/teacher_exam_before.jsp";
    }


    @RequestMapping(value = "editTeacherInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String editTeacherInfo(Teacher teacher, HttpSession session) {
        int index = teacherServiceImpl.updTeacher(teacher);
        if (teacher.getT_pwd() != null && !teacher.getT_pwd().equals("")) {
            teacher.setT_pwd(teacher.getT_pwd());
            session.setAttribute("teacher", teacher);
            teacherServiceImpl.updPwd(teacher);
        }

        if (index >= 1) {
            System.out.println("修改老师信息成功");
            return "修改老师信息成功";
        } else {
            System.out.println("修改老师信息失败");
            return "修改老师信息失败";
        }
    }

    @RequestMapping(value = "deleteTeacher", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String deleteTeacher(String teaId, HttpSession session) {
        int index = teacherServiceImpl.delTeacher(teaId);
        if (index >= 1) {
            return "删除成功";
        } else {
            System.out.println("删除老师失败");
            return "删除失败";
        }
    }

    @RequestMapping("deleteInfo")
    @ResponseBody
    public void deleteInfo(int id) {
        int index = infoServiceImpl.delInfo(id);
        if (index >= 1) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }

    @RequestMapping("exitTeacher")
    public String updPwd(String oldPwd, String newPwd1, String newPwd2, HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        String newPwd = newPwd1;
        if (!oldPwd.equals(teacher.getT_pwd())) {
            session.setAttribute("info", "<script>alert('您输入的密码不正确');</script>");
            if (teacher.getT_manager() == 1) {
                return "redirect:/admin/admin_home.jsp";
            } else {
                return "redirect:/teacher/teacher_home.jsp";
            }
        }
        if (!newPwd1.equals(newPwd2)) {
            session.setAttribute("info", "<script>alert('您两次输入的密码不一致');</script>");
            if (teacher.getT_manager() == 1) {
                return "redirect:/admin/admin_home.jsp";
            } else {
                return "redirect:/teacher/teacher_home.jsp";
            }
        }
        teacher.setT_pwd(newPwd);
        int index = teacherServiceImpl.updPwd(teacher);
        if (index >= 1) {
            System.out.println("密码修改成功");
            session.setAttribute("info", "<script>alert('密码修改成功');</script>");
            session.setAttribute("teachers", teacher);
        } else {
            session.setAttribute("info", "<script>alert('出现未知错误');</script>");
            System.out.println("密码修改失败");
        }
        if (teacher.getT_manager() == 1) {
            return "redirect:/admin/admin_home.jsp";
        } else {
            return "redirect:/teacher/teacher_home.jsp";
        }
    }

    /**
     * admin_save_configs
     */
    @RequestMapping(value = "admin_save_configs", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg adminSaveConfigs(HttpServletRequest request, Config config) {
        System.out.println("***************" + config.getSplitPageCount() + "++++++++++++++++++++++");
        Map<String, String> configMap = new HashMap<>();
        if (config.getTaskSplitTime() != null)
            configMap.put(StaticResources.TASK_SPLIT_TIME, config.getTaskSplitTime());

        if (config.getSplitPageCount() != null)
            configMap.put(StaticResources.SPLIT_PAGE_COUNT, config.getSplitPageCount());

        if (config.getStartSplitTime() != null)
            configMap.put(StaticResources.START_SPLIT_TIME, config.getStartSplitTime());

        if (config.getMaxUploadSize() != null)
            configMap.put(StaticResources.MAX_UPLOAD_SIZE, config.getMaxUploadSize());

        if (config.getMinUploadSize() != null)
            configMap.put(StaticResources.MIN_UPLOAD_SIZE, config.getMinUploadSize());

        try {
            ConfigUtils.setConfig(request, configMap);
        } catch (IOException e) {
            e.printStackTrace();
            return Msg.fail().setMsg("修改设置失敗！");
        }
        return Msg.success().setMsg("修改设置成功！");
    }

    // 查询所有教师信息（分页查询）
    @RequestMapping(value = "getAllTeacher", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Msg getAllTeacher(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, HttpServletRequest request, HttpSession session) {
        // 这不是一个分页查询
        Map config = ConfigUtils.getConfig(request);

        int spiltPageCount = PagingSize.splitPageSize(request);
        // 引入Pagehelper 查询之前调用startPage，传入分码，以及分页大小
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<Teacher> lists = teacherServiceImpl.getAllTeacher();

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Teacher> page = new PageInfo<Teacher>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", page);
        System.out.println("总页码：" + page.getPages());
        System.out.println("总记录数：" + page.getTotal());
        return Msg.success().add("pageInfo", page);
    }


    @RequestMapping("getAllInfosOfStu")
    @ResponseBody
    public Msg getAllInfos(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, HttpServletRequest request, HttpSession session) {

        int spiltPageCount = PagingSize.splitPageSize(request);
        // 引入Pagehelper 查询之前调用startPage，传入分码，以及分页大小
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<Information> lists = infoServiceImpl.getAllInfo();

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Information> page = new PageInfo<Information>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", page);
        System.out.println("总页码：" + page.getPages());
        System.out.println("总记录数：" + page.getTotal());
        return Msg.success().add("pageInfo", page);
    }

    @RequestMapping("getAllInfosOfTea")
    @ResponseBody
    public Msg getAllInfosTea(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, String t_name, HttpServletRequest request, HttpSession session) {

        System.out.println("++++++000" + t_name);

        int spiltPageCount = PagingSize.splitPageSize(request);
        // 引入Pagehelper 查询之前调用startPage，传入分码，以及分页大小
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<Information> lists = infoServiceImpl.selectExamInfoOfTea(t_name);

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Information> pages = new PageInfo<Information>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", pages);
        System.out.println("总页码：" + pages.getPages());
        System.out.println("总记录数：" + pages.getTotal());
        return Msg.success().add("pageInfo", pages);
    }


    /**
     * 根据id查询单个老师
     */
    @RequestMapping("admin_get_teacher")
    @ResponseBody
    public Msg getTeacher(@RequestParam(value = "teaId", defaultValue = "-1") String teaId) {
        //根据id查询单个老师
        Teacher teacher = teacherServiceImpl.selTeacher(teaId);
        System.out.println("teacher:" + teacher);
        return Msg.success().add("teacher", teacher);
    }

    /**
     * 保存教师
     */
    @RequestMapping(value = "addTeacher", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg saveTeacher(Teacher teacher) {
        System.out.println(teacher.getT_username() + "*******************");
        int count = teacherServiceImpl.selTeaNumOfId(teacher.getT_username());
        if (count > 0) return Msg.fail().add("va_msg", "添加失败！该工号教师已存在！");
        else {
            teacherServiceImpl.addTeacher(teacher);
            return Msg.success();
        }
    }

    /**
     * 批量删除教师
     */
    @RequestMapping("admin_delete_teachers")
    @ResponseBody
    public Msg updateTeachers(@RequestParam(value = "del_ids", defaultValue = "") String del_ids) {
        System.out.println("要删除的id有：" + del_ids);
        if (del_ids.length() == 0) return Msg.fail().setMsg("没有任何需要删除的教师被选中！");

        Set<String> ids = new HashSet<>();

        String[] str_ids = del_ids.split("-");
        //组装id的集合
        for (String string : str_ids) {
            ids.add(string);
        }

        int count = teacherServiceImpl.deleteTeacherBatch(ids);
        if (count > 0)
            return Msg.success().setMsg("删除成功！");
        else
            return Msg.fail().setMsg("出现异常啦！");
    }

    @RequestMapping("teacherInformation")
    @ResponseBody
    public void addInfo(Information info, HttpSession session) {
        Date currDate = Calendar.getInstance().getTime();
        info.setTimes(currDate);
        int index = infoServiceImpl.insertInfo(info);
        if (index >= 1) {
            System.out.println("消息发布成功");
        } else {
            System.out.println("消息发布失败");
        }
    }

    // 教师/管理员登录
    @RequestMapping("teacherLogin")
    public String login(Teacher teacher, HttpSession session) {
        Teacher tea = teacherServiceImpl.login(teacher);
        if (tea != null) {
            session.setAttribute("teacher", tea);
            session.setAttribute("teachers", teacherServiceImpl.getAllTeacher());
            session.setAttribute("info", "登录成功");
            if (tea.getT_manager() == 1) {
                return "redirect:/success/adminSuc.jsp";
            }
            if (tea.getT_manager() == 0) {
                return "redirect:/success/teacherSuc.jsp";
            }
            System.out.println("登录出错");
        }

        // 查询管理员数量
        int count_manager = teacherServiceImpl.getManagerCount();
        if (count_manager <= 0 && teacher.getT_manager() == 1 && teacher.getT_username().equals("admin")
                && teacher.getT_pwd().equals("admin")) {
            Teacher tea_admin = new Teacher();
            tea_admin.setT_manager(1);
            tea_admin.setT_name("默认管理员");
            tea_admin.setT_pwd("admin");
            tea_admin.setT_username("admin");
            session.setAttribute("teacher", tea_admin);
            session.setAttribute("teachers", teacherServiceImpl.getAllTeacher());
            session.setAttribute("info", "登录成功");
            System.out.println(tea_admin);
            return "redirect:/success/adminSuc.jsp";
        }
        session.setAttribute("info", "登录失败");
        return "redirect:/success/loginError.jsp";
    }

    // 下载学生答案
    @RequestMapping("teacher_download")
    public void downLoadAnswer(String name, HttpServletRequest req, HttpServletResponse res, HttpSession session) {
        String folderPath = req.getServletContext().getRealPath("/files/" + name);
        try {
            FileHelper.downloadZip(req, res, folderPath, name);
        } catch (IOException e) {
            System.out.println("下载学生答案失败！");
            e.printStackTrace();
        }
        System.out.println("下载学生答案成功！");
    }

    // 批量导入学生名单
    @RequestMapping(value = "saveExcel", method = RequestMethod.POST, produces = {"text/html;charset=utf-8"})
    @ResponseBody
    public String saveExcel(MultipartFile file, @RequestParam(value = "stu_exam", defaultValue = "java") String stu_exam, HttpServletRequest req, HttpSession session) {
        System.out.println(stu_exam + "**********************");
        int index = studentServiceImpl.saveExcel(file, stu_exam, req, session);
        if (index == 0) {
            return "{\"infos\":\"100\"}";
        } else {
            if (index == 1) {
                return "{\"infos\":\"该文件已存在服务器，改个名字试试！\"}";
            } else if (index == 2) {
                return "{\"infos\":\"出现未知错误！\"}";
            } else {
                return "{\"infos\":\"名单存在重复信息！\"}";
            }
        }
    }

    // 批量导入教师名单
    @RequestMapping(value = "saveTeaExcel", method = RequestMethod.POST)
    @ResponseBody
    public String saveTeaExcel(MultipartFile file, HttpServletRequest req) {
        int index = teacherServiceImpl.saveTeaExcel(file, req);

        if (index == 0) {
            return "{\"infos\":\"100\"}";
        } else {
            if (index == 1) {
                return "{\"infos\":\"该文件已存在服务器，改个名字试试！\"}";
            } else if (index == 2) {
                return "{\"infos\":\"出现未知错误！\"}";
            } else {
                return "{\"infos\":\"名单存在重复信息！\"}";
            }
        }
    }

    @RequestMapping(value = "addStudent", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg addStudent(Student student, HttpSession session) {
        if (student.getStu_exam() == null) {
            student.setStu_exam((String) session.getAttribute("examStartName"));
        }
        int index = studentServiceImpl.insStudent(student);
        if (index >= 1) {
            return Msg.success().setMsg("添加成功");
        } else {
            return Msg.success().setMsg("添加失败");
        }
    }

    @RequestMapping(value = "deleteOneStudent", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg deleteOneStudent(String stuName, String stuExam) {
        System.out.println(stuExam + "+++++++++" + stuName);
        int count = teacherServiceImpl.delStudentExam(stuName, stuExam);
        if (count > 0)
            return Msg.success().setMsg("删除成功！");
        else
            return Msg.fail().setMsg("出现异常啦！");
    }

    @RequestMapping(value = "getBeforeStuInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Msg getBeforeStuInfo(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, String exam, String e_teacher, HttpServletRequest request, HttpSession session) {

        System.out.println(exam + "++++++++++++++++++++**************" + e_teacher);
        int spiltPageCount = PagingSize.splitPageSize(request);
        // 查询之前调用startPage，传入分码，以及分页大小
        PageHelper.startPage(pageNum, spiltPageCount);
        // startPage紧跟的查询就是分页查询
        List<Student> lists = studentServiceImpl.selAllStudents(exam, e_teacher);

        // 使用pageInfo包装查询后的结果，只需要将pageInfo交给页面就行了。
        // 封装了详细的分页信息,包括有我们查询出来的数据，传入连续显示的页数
        PageInfo<Student> page = new PageInfo<Student>(lists, StaticResources.navigatePages);
        session.setAttribute("pageInfo", page);
        System.out.println("总页码：" + page.getPages());
        System.out.println("总记录数：" + page.getTotal());
        return Msg.success().add("pageInfo", page);
    }

    @RequestMapping("teacher_get_student")
    @ResponseBody
    public Msg getStudent(@RequestParam(value = "stuId", defaultValue = "000") String stuId, @RequestParam(value = "stuExam", defaultValue = "000") String stuExam) {
        //根据id查询单个老师
        Student student = studentServiceImpl.selStudentByIdExam(stuId, stuExam);
        return Msg.success().add("student", student);
    }

    @RequestMapping(value = "editStuInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String editStuInfo(Student student, HttpSession session) {
        int index = studentServiceImpl.editStudent(student);
        if (index >= 1) {
            System.out.println("修改老师信息成功");
            return "修改老师信息成功";
        } else {
            System.out.println("修改老师信息失败");
            return "修改老师信息失败";
        }
    }
}
